<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * BuildingList controller
 */
class BuildingList extends Front_Controller
{
    // private $_listURL = "/buildings/front/buildingList/index/";
    private $_listURL = "/building/";

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 3.0版本楼盘列表页
     * @author zephan <zephanliu@gmail.com>
     */
    public function index($cityCode) {

        if (empty($cityCode)) {
            // 默认调整到上海楼盘列表
            redirect($this->_listURL.'shanghai', 'auto', 302);
        }
        //if (is_fang90_server_name()) redirect(config_item('fang90.domain'));

        $get = $this->input->get();
        $page = isset($get['page']) ? $get['page'] : 1;
        $order = isset($get['order']) ? $get['order'] : null;
        $condition = isset($get['condition']) ? $get['condition'] : null;
        //今日头条渠道参数处理
        $buildingId = isset($get['id']) ? $get['id'] : '';
        // 区域
        $d = isset($get['d']) ? $get['d'] : null; 
        // 类型
        $t = isset($get['t']) ? $get['t'] : null;
        // 特色
        $tg = isset($get['tg']) ? $get['tg'] : null;
        // 价格
        $p = isset($get['p']) ? $get['p'] : null;
        // 加载模型
        $this->load->model('hometop/hometop_model');
        $this->load->model('hotcity/hotcity_model');
        $this->load->model('area/area_model');
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingsinfo_model');
        $this->load->model('buildings/buildingstag_model');
        $this->load->model('price/price_model');
        $this->load->library('user_agent');

        $limit = 5;
        // 根据板块获取所有已开通的城市
        $citiestmp = $this->area_model->select("area_id,area_name,code,plates")->where('active=1 and deleted=0')->find_all();
        $area_block_name = area_block_name();
        foreach ($citiestmp as $key => $val) {
            $cities[$area_block_name[$val->plates]][] = $val;
        }
        $data['cities'] = $cities;
        // 已选的筛选条件
        $queryArr = [];
        // 地区类型 0:country,1:province,2:city,3:district
        $city = $this->area_model->select('area_id,area_name,code')->find_by(['code'=>$cityCode, 'area_type'=>2, 'active'=>1]);
        if (!$city) redirect("/", 'auto', '302');
        $data['city'] = $city;
        $districtArr = $this->area_model->select('area_id,area_name as name')->where('parent_id', $city->area_id)->find_all();
        $url = $this->_listURL.$cityCode;
        $normalActive = 1;
        foreach ($districtArr as $key => $val) {
            $queryData['d'] = $val->area_id;
            $districtArr[$key]->url = "{$url}?".$this->query_data($queryData, $get);
            $districtArr[$key]->url_active = ($d == $val->area_id) ? 1 : 0;
            $districtArr[$key]->disabled = 0;
            if ($d == $val->area_id) {
                $normalActive = 0;
                $queryDistrict = $districtArr[$key];
                $queryDistrict->url = "{$url}?".$this->query_data(['d'=>''], $get);
                $queryArr[] = $queryDistrict;
            }
        }
        array_unshift($districtArr, (object)['name'=>'不限', 'url'=>"{$url}?".$this->query_data(['d'=>''], $get), 'url_active'=>$normalActive, 'disabled'=>0]);
        $data['districts'] = &$districtArr;
        // 热门楼盘
        // $hotBuildings = $this->buildings_model->select("id,name")->where("city_id = {$city->area_id}")->order_by("rand()")->limit(2)->find_all();
        $hotBuildings = $this->buildings_model->select("id,name")->where("city_id = {$city->area_id}")->limit(2)->find_all();
        $data['hot_buildings'] = $hotBuildings;
        // 楼盘类型
        $buildingType = building_room_type();
        $queryData = [];
        $normalActive = 1;
        foreach ($buildingType as $key => $val) {
            $queryData['t'] = $key;
            $type = (object)['url'=>"{$url}?".$this->query_data($queryData, $get), 
                                'name'=>$val, 
                                'url_active'=>($t == $key) ? 1 : 0];
            $buildingType[$key] = $type;
            if ($t == $key) {
                $normalActive = 0;
                $queryBuildingType = $buildingType[$key];
                $queryBuildingType->url = "{$url}?".$this->query_data(['t'=>''], $get);
                $queryArr[] = $queryBuildingType;
            }
        }
        // array_unshift($buildingType, (object)['name'=>'不限', 'url'=>"{$url}?".$this->query_data(['t'=>''], $get), 'url_active'=>$normalActive]);
        $data['building_type'] = $buildingType;
        // 城市价格
        $cityPrice = $this->price_model->select('price,price_digit,city_id')->where("city_id = {$city->area_id} AND deleted = 0")->find_all();
        $queryData = [];
        $priceWhere = '';
        $normalActive = 1;
        if(!empty($cityPrice)){
            foreach ($cityPrice as $key => $val) {
                $pVal = 'p'.($key+1);
                $priceExplode = explode('-', $val->price_digit);
                $val->where = "ave_price >= {$priceExplode[0]} AND ave_price < {$priceExplode[1]}";
                if (empty($priceExplode[0])) {
                    $val->where = "ave_price < {$priceExplode[1]}";
                } else if (empty($priceExplode[1])) {
                    $val->where = "ave_price > {$priceExplode[0]}";
                }
                $queryData['p'] = $pVal;//$val->val;
                $cityPrice[$key]->name = $val->price;
                $cityPrice[$key]->url = "{$url}?".$this->query_data($queryData, $get);
                $cityPrice[$key]->url_active = ($p == $pVal) ? 1 : 0;
                // 价格条件
                if ($p == $pVal) {
                    $normalActive = 0;
                    $priceWhere = " AND {$val->where}";
                    $queryPrice = $cityPrice[$key];
                    $queryPrice->url = "{$url}?".$this->query_data(['p'=>''], $get);
                    $queryArr[] = $queryPrice;
                }
            }
        }

        // array_unshift($cityPrice, (object)['name'=>'不限', 'url'=>"{$url}?".$this->query_data(['p'=>''], $get), 'url_active'=>$normalActive]);
        $data['city_price'] = $cityPrice;
        // 排序数据
        $orderClass = ['o1'=>'order-active-up', 'o2'=>'order-active-down', 'o3'=>'order-active-up', 'o4'=>'order-active-down'];
        $queryData = [];
        $orderArr = [(object)['name'=>'价格', 'val'=>'o3'], (object)['name'=>'开盘时间', 'val'=>'o1']];
        if(!empty($orderArr)){
            foreach ($orderArr as $key => $val) {
                $orderUrl = $val->val;
                $aClass = 'order-up';
                if ($val->val == $order) {
                    $orderUrl = $val->name == '价格' ? 'o4' : 'o2';
                }
                if (isset($order)) {
                    if ((($order == 'o1' || $order == 'o2') && $val->name == '开盘时间')) {
                        $aClass = $orderClass[$order];
                    }
                    if ((($order == 'o3' || $order == 'o4') && $val->name == '价格')) {
                        $aClass = $orderClass[$order];
                    }
                }
                $queryData['order'] = $orderUrl;
                $orderArr[$key]->url = "{$url}?".$this->query_data($queryData, $get);
                $orderArr[$key]->a_class = $aClass;
                if (in_array($order, ['o2', 'o4'])) {
                    $orderArr[$key]->url = "{$url}?".$this->query_data(['order'=>''], $get);
                }
            }
        }
        $data['order_arr'] = $orderArr;
        // 楼盘数据
        $where = "deleted = 0 AND publish = 1";
        // 区域条件
        $where .= $d == null ? " AND city_id = {$city->area_id}" : " AND district_id = {$d}";
        // 价格条件
        $where .= $priceWhere;

        $buildingTable = $this->buildings_model->get_table();
        $infoTable = $this->buildingsinfo_model->get_table();
        //头条数据
        if(!empty($buildingId) && $page == 1 ){
            $buildingByJrtt = $this->buildings_model->select("*")
                                                ->join($infoTable, "{$buildingTable}.id = {$infoTable}.building_id")
                                                ->find($buildingId);
            if( $buildingByJrtt ){ $where .= " and {$buildingTable}.`id` != {$buildingId}"; }
        }
        $orderBy = $this->order_by($order) ? : ["{$buildingTable}.`id`"=> "DESC"];
        $buildings = $this->buildings_model->select("*")
                                            ->where($where)
                                            ->join($infoTable, "{$buildingTable}.id = {$infoTable}.building_id")
                                            ->limit($limit, ($page-1)*$limit)
                                            ->order_by($orderBy)
                                            ->find_all();
        //将头条指定数据插入数组第一个
        if( isset($buildingByJrtt) && !empty($buildingByJrtt) ){
            if (!is_array($buildings)) $buildings = [];
            array_unshift( $buildings, $buildingByJrtt);
        }                                 
        if ($buildings) {
            foreach ($buildings as $key => $val) {
                $tags = $this->buildingstag_model->tags($val->building_id);
                if ($val->price_desc != '') {
                    $price = $val->price_desc;
                    $number = preg_replace('/\D/s', '', $price);  
                    $buildings[$key]->price_desc = str_replace($number, "<span>¥".number_format($number)."</span>", $price);
                }
                $buildings[$key]->tags = isset($tags['putong']) ? $tags['putong'] : [];
                $district = $this->area_model->select('area_id,area_name')->find($val->district_id);
                $buildings[$key]->district = $district;
                $photos = $this->buildings_model->getBuildingPhotos($val->building_id);
                $buildings[$key]->cover = $photos['cover']['pc'][0];
                $buildings[$key]->ave_price = number_format($val->ave_price);
                // foreach ($districtArr as $k => $v) {
                //     if (isset($v->area_id) && ($val->district_id == $v->area_id)) $districtArr[$k]->disabled = 0;
                // }
            }
        }
        $data['buildings'] = $buildings;
        $currentQuery = $this->current_url_query($get);
        $data['current_query'] = $currentQuery;
        // dump($buildings);
        // 分页
        $currentUrl = "{$url}?".$currentQuery;
        $totalRows = $this->buildings_model->select("*")->where($where)->count_all();
        $this->load->library('pagination');
        $this->pager['base_url']    = $currentUrl;
        $this->pager['total_rows']  = $totalRows;
        $this->pager['per_page']    = $limit;
        $this->pager['use_page_numbers'] = true;
        $this->pager['page_query_string'] = true;
        $this->pager['enable_query_strings'] = true;
        $this->pager['query_string_segment'] = 'page';
        $this->pagination->initialize($this->pager);
        // echo $this->pagination->create_links();

        $data['query_arr'] = $queryArr;
        $data['city_code'] = $cityCode;
        $data['list_url'] = $url;
        $data['qd'] = isset($get['qd']) ? $get['qd'] : '';
        $data['listurl'] = $this->_listURL;

        $this->load->model('channel/channel_model');
        $channel = $data['qd'];
        $hasChannel = $this->channel_model->count_by('code', $channel);
        $data['show_qyyx58'] = ($this->agent->is_mobile() && !in_array($channel, ['baidu', 'bd1', 'bd', 'bdka', 'other']) && $hasChannel) ? 1 : 0;
        $ms = date("Hi");
        if ($this->agent->is_mobile() 
            && in_array($channel, ['baidu', 'bd1', 'bd']) 
            && (($ms >= 1830 && $ms <= 2359) || ($ms >= 0 && $ms <= 0859) || in_array(date("N"), [6,7]))) {
            // 这个条件下百度相关渠道
            $data['show_qyyx58'] = 1;
        }

        // dump($data);
        // 加载视图
        if ($condition) {
            $this->load->view('front/building/condition', $data);
        } else {
            $this->load->view('front/building/list', $data);
        }
    }

    /**
     * 楼盘数据排序规则
     * @param  string $order key
     * @return mixed
     * @author zephan <zephanliu@gmail.com>
     */
    private function order_by($order) {
        $orderBy['o1'] = ['open_time'=>'ASC'];
        $orderBy['o2'] = ['open_time'=>'DESC'];
        $orderBy['o3'] = ['ave_price'=>'ASC'];
        $orderBy['o4'] = ['ave_price'=>'DESC'];
        return isset($orderBy[$order]) ? $orderBy[$order] : '';
    }

    /**
     * 楼盘当前页面的筛选参数
     * @param  array $get get
     * @return string
     * @author zephan <zephanliu@gmail.com>
     */
    private function current_url_query($get) {
        $queryData = [];
        if (isset($get['d'])) {
            $queryData['d'] = $get['d'];
        }
        if (isset($get['t'])) {
            $queryData['t'] = $get['t'];
        }
        if (isset($get['tg'])) {
            $queryData['tg'] = $get['tg'];
        }
        if (isset($get['p'])) {
            $queryData['p'] = $get['p'];
        }
        if (isset($get['order'])) {
            $queryData['order'] = $get['order'];
        }
        if (isset($get['id'])) {
            $queryData['id'] = $get['id'];
        }
        if (isset($get['qd'])) {
            $queryData['qd'] = $get['qd'];
        }
        return http_build_query($queryData);
    }

    /**
     * 生成对应的url
     * @param  array $queryData
     * @param  array $get       get
     * @return string
     * @author zephan <zephanliu@gmail.com>
     */
    private function query_data($queryData, $get) {
        if (isset($get['d']) && !isset($queryData['d'])) {
            $queryData['d'] = $get['d'];
        }
        if (isset($get['t']) && !isset($queryData['t'])) {
            $queryData['t'] = $get['t'];
        }
        if (isset($get['tg']) && !isset($queryData['tg'])) {
            $queryData['tg'] = $get['tg'];
        }
        if (isset($get['p']) && !isset($queryData['p'])) {
            $queryData['p'] = $get['p'];
        }
        if (isset($get['order']) && !isset($queryData['order'])) {
            $queryData['order'] = $get['order'];
        }

        if (isset($queryData['d']) && $queryData['d'] == null) unset($queryData['d']);
        if (isset($queryData['t']) && $queryData['t'] == null) unset($queryData['t']);
        if (isset($queryData['tg']) && $queryData['tg'] == null) unset($queryData['tg']);
        if (isset($queryData['p']) && $queryData['p'] == null) unset($queryData['p']);
        if (isset($queryData['order']) && $queryData['order'] == null) unset($queryData['order']);

        return http_build_query($queryData);
    }

}